package br.org.bhs.jump;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.game.GameCanvas;

public class TesteDesenho extends GameCanvas implements Runnable
{
    private int centroX;
    private int centroY;
    private int alturaTela;
    private int larguraTela;
    private StringBuffer horario;
    private boolean deuErro = false;
    private String erro;


    private Graphics graphics;
    private boolean jogoRodando = true;

    public TesteDesenho()
    {
        super(false);
        this.graphics = getGraphics();
        this.alturaTela = getHeight();
        this.larguraTela = getWidth();
        this.centroX = larguraTela / 2;
        this.centroY = alturaTela / 2;
    }

    public void iniciar()
    {
        Thread threadJogo = new Thread(this);
        threadJogo.start();
    }

    public void run()
    {
        try
        {
            int horas;
            int minutos;
            int segundos;

            while (jogoRodando)
            {
                Calendar calendario = Calendar.getInstance(TimeZone.getDefault());
                calendario.setTime(new Date());

                horas = calendario.get(Calendar.HOUR_OF_DAY);
                minutos = calendario.get(Calendar.MINUTE);
                segundos = calendario.get(Calendar.SECOND);

                horario = new StringBuffer();

                if (horas < 10) horario.append("0");
                horario.append(horas);
                horario.append(":");

                if (minutos < 10) horario.append("0");
                horario.append(minutos);
                horario.append(":");

                if (segundos < 10) horario.append("0");
                horario.append(segundos);

                paint(graphics);
            }

        } catch (Exception ex) 
        {
            System.out.println(ex.getMessage());
            deuErro = true;
            erro = ex.getMessage();
            paint(graphics);
        }
    }

    public void paint(Graphics g)
    {
        if (!deuErro)
        {
            g.setColor(0, 0, 0);
            g.fillRect(0, 0, larguraTela, alturaTela);
            g.setColor(255, 255, 0);
            g.drawString(horario.toString(), centroX, centroY, Graphics.HCENTER | Graphics.BASELINE);
        }
        else
        {
            g.setColor(255, 255, 255);
            g.fillRect(0, 0, larguraTela, alturaTela);
            g.setColor(0, 0, 0);
            g.drawString(erro, 5, 5, Graphics.LEFT | Graphics.TOP);
        }

        flushGraphics();
    }


    protected void keyPressed(int keyCode)
    {
        if ((getGameAction(keyCode) == FIRE) || (keyCode == KEY_NUM5))
        {
            jogoRodando = false;
            MidletTeste midletTeste = MidletTeste.getInstance();
            midletTeste.destroyApp(true);
            midletTeste.notifyDestroyed();
        }
    }
}
